﻿using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Mvc;
using Qiniu.Storage;
using Qiniu.Util;
using VOL.Core.Utilities;
using VOL.SmartMecial.IServices.EvaluateNurseCare;
using VOL.Entity.AttributeManager;
using VOL.SmartMecial.Dtos;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Microsoft.AspNetCore.StaticFiles;
using System.IO;


namespace VOL.WebApi.Controllers.SmartMecial
{
    [Route("api/InAssessController")]
    [PermissionTable(Name = "InAssessController")]
    public class InAssessController : ControllerBase
    {

        private readonly IInAssessServices _inAssessServices;
        public InAssessController(IInAssessServices inAssessServices)
        {
            _inAssessServices = inAssessServices;
        }
        /// <summary>
        /// 添加入院评估
        /// </summary>
        /// <param name="inAssess"></param>
        /// <returns></returns>
        [HttpPost("AddInAssess")]
        public async Task<WebResponseContent> AddInAssess([FromBody] Entity.DomainModels.InAssess inAssess)
        {
            var result = await _inAssessServices.AddInAssess(inAssess);
            var webResponseContent = WebResponseContent.Instance.OK("添加成功", result);
            return webResponseContent;
        }

        /// <summary>
        /// 入院评估电子签名上传
        /// </summary>
        /// <param name="writeImage"></param>
        /// <returns></returns>
        [HttpPost("UpdateImg")]
        public IActionResult UpdateImg([FromBody] string writeImage)
        {
            string base64Signurl = writeImage?.Trim();
            if (string.IsNullOrEmpty(base64Signurl))
            {
                return Ok("signurl无效");
            }

            byte[] data;
            data = Convert.FromBase64String(base64Signurl);

            //请到官网申请七牛云账号、秘钥
            var accessKey = "OecJqF2vFd_TrnrYa-xCJWu6u6hbKSY_YbXtV96i";
            var secretKey = "DbFMydQXQ_qK9QNHSvyH4cRHOxrMPIShzQsuBZGk";

            Mac mac = new Mac(accessKey, secretKey);
            //保存到七牛云上的文件目录
            string saveKey = "MyImg/" + Guid.NewGuid() + ".jpg";
            // 存储空间名
            string Bucket = "battlefieldone";
            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            // 设置要上传的目标空间
            putPolicy.Scope = Bucket;

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略的过期时间(单位:秒)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            // 生成上传token
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            Config config = new Config();
            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Qiniu.Storage.Zone.ZONE_CN_North;
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            // 数据流上传
            FormUploader fu = new FormUploader(config);
            //七牛云支持 stream流、MemoryStream流、Filestream流上传
            var result = fu.UploadData(data, saveKey, token, null);
            Console.WriteLine(result);

            var imgUrl = "http://svgpl38o2.hb-bkt.clouddn.com/" + saveKey;
            Console.WriteLine(imgUrl);
            return Ok(imgUrl);
        }


        /// <summary>
        /// 显示入院评估表单
        /// </summary>
        /// <param name="pageDto"></param>
        /// <returns></returns>
        [HttpGet("ShowInAssess")]
        public async Task<WebResponseContent> ShowInAssess(PageDTO pageDto)
        {
            var result = await _inAssessServices.ShowInAssess(pageDto);
            var webResponseContent = WebResponseContent.Instance.OK("显示成功", result);
            return webResponseContent;
        }
        /// <summary>
        /// 获取所有入院评估数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllInAssess")]
        public async Task<WebResponseContent> GetAllInAssess()
        {
            var result = await _inAssessServices.GetAllInAssess();
            var webResponseContent = WebResponseContent.Instance.OK("获取成功", result);
            return webResponseContent;
        }

        /// <summary>
        /// 导出入院评估单
        /// </summary>
        /// <returns></returns>
        [HttpGet("ExportExcel")]
        public async Task<ActionResult> ExportExcel() 
        {
            try
            {
                byte[] data = null;
                string contextType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
                string fileName = "入院评估单.xlsx";
                //新的Excel⼯作簿
                IWorkbook book = new XSSFWorkbook();
                //创建⼀个sheet
                ISheet sheet = book.CreateSheet();
                //创建第⼀⾏
                IRow row1 = sheet.CreateRow(0);
                //给第一行的每个单元格赋值
                row1.CreateCell(0).SetCellValue("入院评估主键");
                row1.CreateCell(1).SetCellValue("患者编码");
                row1.CreateCell(2).SetCellValue("护士编码");
                row1.CreateCell(3).SetCellValue("入院类型");
                row1.CreateCell(4).SetCellValue("意识状态");
                row1.CreateCell(5).SetCellValue("语言");
                row1.CreateCell(6).SetCellValue("活动能力");
                row1.CreateCell(7).SetCellValue("视力");
                row1.CreateCell(8).SetCellValue("听力");
                row1.CreateCell(9).SetCellValue("大便");
                row1.CreateCell(10).SetCellValue("小便");
                row1.CreateCell(11).SetCellValue("签名");
                var getInAssessList = await _inAssessServices.GetAllInAssess();
                int rowIndex = 1;
                foreach (var item in getInAssessList) 
                {
                    IRow row = sheet.CreateRow(rowIndex);
                    row.CreateCell(0).SetCellValue(item.Id);
                    row.CreateCell(1).SetCellValue(item.PatientCode);
                    row.CreateCell(2).SetCellValue(item.NurseCode);
                    row.CreateCell(3).SetCellValue(item.InType);
                    row.CreateCell(4).SetCellValue(item.Sense);
                    row.CreateCell(5).SetCellValue(item.Language);
                    row.CreateCell(6).SetCellValue(item.Activity);
                    row.CreateCell(7).SetCellValue(item.Vision);
                    row.CreateCell(8).SetCellValue(item.Hearing);
                    row.CreateCell(9).SetCellValue(item.MaxExcrete);
                    row.CreateCell(10).SetCellValue(item.MinExcrete);
                    row.CreateCell(11).SetCellValue(item.SignUrl);

                    rowIndex++;
                }
                using (MemoryStream memoryStream = new MemoryStream()) 
                {
                    //工作表 写入内存流中
                    book.Write(memoryStream);
                    //内存流 赋给数据字节数组中
                    data = memoryStream.ToArray();

                }
                
                return File(data, contextType, fileName);
            }
            catch (Exception)
            {

                throw;
            }
        
        }






    }
}
